package com.stake.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;

//@Controller
//@RequestMapping("/home") 
public class TicTacController {
	
	ChannelService channelService2;
	
	//@RequestMapping("/listen.htm") 
	public ModelAndView ticTacTest(@RequestParam("u") String userParam, HttpServletResponse response, HttpSession session){
		session.setAttribute("userParam", userParam);
		ChannelService channelService = ChannelServiceFactory.getChannelService();
		String token = channelService.createChannel(userParam);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("token", token);
		return new ModelAndView("tictacTemplate2", model);
	}
	
	//@RequestMapping("/testSend.htm") 
	public @ResponseBody String testReceive(HttpSession session, HttpServletRequest request){
		final String thisUser = (String) session.getAttribute("userParam"); 
		ChannelService channelService = ChannelServiceFactory.getChannelService();
		channelService.sendMessage(new ChannelMessage("test345", "test message from " + thisUser)); 
		
		return "ok";
	}
	
	//@RequestMapping("/cometPublish.htm") 
	public @ResponseBody String cometPublishTest(HttpSession session, HttpServletRequest request){
		
		return "ok";
	}
	
	//@RequestMapping("/init.htm") 
	public @ResponseBody String init(){
		return "{cometd:this,action:\"handshake\",successful:true,state:this.state()}";
	}
	
	public static void main(String... strings ){
		int x = 0;
		String s = "str";
		try {
			new String();
			s = null;
			throw new Exception();
		} catch (Exception e) {
			e.printStackTrace();
			int y = 4/x;
			//System.out.println(s.length());
		} finally {
			System.out.println("finally.. "); 
		}
	}
}
